package com.xmutca.sso.sdk.filter;

import com.xmutca.core.common.Result;
import com.xmutca.sso.common.util.ShiroWebUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: 彭伟煌(pengweihuang@xmutca.com)
 * @create: 2016-08-24 21:21
 */
public class CustomerAuthcFilter extends FormAuthenticationFilter {

    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        if (ShiroWebUtils.isAjaxRequest(servletRequest)) {
            //如果是ajax形式
            Result<String> result = new Result<>(Result.Status.NEED_LOGIN, "您当前尚未授权");
            ShiroWebUtils.writeJSONString((HttpServletResponse)response, result);
            return;
        }

        String redirectUrl = servletRequest.getRequestURL().toString();
        String loginUrl = getLoginUrl();
        ShiroWebUtils.redirectToSavedRequestForCustomerRedirectUri(request, response, String.format("%s?redirectUrl=%s", loginUrl, redirectUrl));
    }
}
